﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;

///Developed By Indie Studio
///https://assetstore.unity.com/publishers/9268
///www.indiestd.com
///info@indiestd.com

namespace IndieStudio.BugsBang.Utility
{
	[DisallowMultipleComponent]
	public class ImageFill : MonoBehaviour
	{
		/// <summary>
		/// The fill speed.
		/// </summary>
		[Range(0,2)]
		public float speed = 1f;

		/// <summary>
		/// Fill from value.
		/// </summary>
		public float fromValue = 0f;

		/// <summary>
		/// Fill to value.
		/// </summary>
		public float toValue = 1f;

		/// <summary>
		/// A temp value.
		/// </summary>
		private float tempValue;

		/// <summary>
		/// The image references.
		/// </summary>
		public Image image;

		/// <summary>
		/// Whether to run on start or not.
		/// </summary>
		public bool runOnStart;

		/// <summary>
		/// Whether the fill process is running or not.
		/// </summary>
		[HideInInspector]
		public bool isRunning;

		/// <summary>
		///  On finish unity event.
		/// </summary>
		public UnityEvent onFinishEvent;

		// Use this for initialization
		void Start ()
		{
			//Setting up references

			if (image == null) {
				image = GetComponent<Image> ();
			}

			if (runOnStart) {
				Run ();
			}
		}
	
		void Update(){
			if (!isRunning) {
				return;
			}

			tempValue = Mathf.MoveTowards (tempValue, toValue, Time.deltaTime * speed);

			image.fillAmount = tempValue;

			if (Mathf.Approximately (tempValue, toValue)) {
				onFinishEvent.Invoke ();
				isRunning = false;
			}
		}

		/// <summary>
		/// Reset to the final value.
		/// </summary>
		public void ResetToFinalValue(){
			image.fillAmount = toValue;
		}

		/// <summary>
		/// Reset to the first value.
		/// </summary>
		public void ResetToFirstValue(){
			image.fillAmount = fromValue;
		}

		/// <summary>
		/// Run this instance.
		/// </summary>
		public void Run(){
			tempValue = fromValue;
			isRunning = true;
		}
	}
}